package self.crypt.web;

import java.util.Date;
import java.util.logging.Logger;
import java.io.IOException;
import java.io.PrintWriter;

import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.bouncycastle.crypto.CryptoException;

import self.crypt.db.SaveEncryptedData;
import self.crypt.factory.PMF;
import self.crypt.logic.EncryptAndDecrypt;

public class EncryptorServlet extends HttpServlet {
	private static final long serialVersionUID = 8947008210561166684L;
	private static final Logger log = Logger.getLogger(EncryptorServlet.class
			.getName());

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		PersistenceManager pmf =null;
		String id = request.getParameter("id");
		String passPhrase = request.getParameter("key");
		String dataToEncrypt = request.getParameter("dataToEncrypt");
		String emailAddress = request.getUserPrincipal().getName();
		byte[] encryptedData = null;
		response.setContentType("text/plain");
		PrintWriter out = response.getWriter();
		log.info("User email address is::" + emailAddress);
		if (id != null && id.length() > 0) {
			if (passPhrase != null && passPhrase.length() > 0) {
				if (dataToEncrypt != null && dataToEncrypt.length() > 0) {
					try {
						encryptedData = encryptData(passPhrase, dataToEncrypt);
						SaveEncryptedData sed = new SaveEncryptedData();
						sed.setCreateDate(new Date());
						sed.setModifiedDate(new Date());
						sed.setEmailAddress(emailAddress);
						sed.setEncryptedData(encryptedData);
						sed.setUniqueId(id);
						pmf = PMF.get().getPersistenceManager();
						pmf.makePersistent(sed);
						out.println("Encryption success...");
					} catch (Exception e) {
						out.println("Exception while encrypting the data::"
								+ e.getMessage());
					}
					finally{
						if(pmf != null){
							pmf.close();
						}
					}
				} else {
					response.sendRedirect("/util/encrypt.jsp?error=No data");
				}
			} else {
				response.sendRedirect("/util/encrypt.jsp?error=No passphrase");
			}
		} else {
			response.sendRedirect("/util/encrypt.jsp?error=No unique Id");
		}
	}

	private byte[] encryptData(String key, String data) throws CryptoException {
		EncryptAndDecrypt encAndDec = new EncryptAndDecrypt(key);
		byte[] encryptedDataArray = encAndDec.encryptString(data);
		return encryptedDataArray;
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		doGet(request, response);
	}
}
